<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>水平居中案例</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    .box {
      width: 500px;
      height: 500px;
      border: 1px solid #000;
      margin: 0 auto;
      position: relative;
    }

    .son {
      width: 200px;
      height: 200px;
      background-color: pink;
      /* 方法1：直接margin:0 auto */
      /* margin: 0 auto; */

      /* 方法2：利用定位加位移 */
      position: absolute;
      left: 50%;
      top: 0;
      transform: translateX(-50%);
    }
  </style>
</head>

<body>
  <div class="box">
    <div class="son"></div>
  </div>
</body>

</html>